<template>
	<el-cascader v-model="cityValue" ref="cityCascaderRef" placeholder="选择省市区" v-bind="$attrs" :options="options" :props="cascaderProps" />
</template>

<script setup lang="ts" name="cityCascader">
import { computed, onMounted, ref, watch } from 'vue';
import { getCityList } from '/@/api/api';
import type { CascaderProps } from 'element-plus';

// 定义父组件传过来的值
const props = defineProps({
	// 是否禁用
	modelValue: [],
	leaf: {
		type: Number,
		default: 2,
	},
	props: {
		type: Object,
		default: () => ({}),
	},
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['update:modelValue', 'update:label']);

const cityCascaderRef = ref();
const options = ref([]);

const cascaderProps: CascaderProps = {
	label: 'areaName',
	value: 'areaId',
	...props.props,
};

const cityValue = computed({
	get() {
		return props.modelValue;
	},
	set(val: string) {
		emit('update:modelValue', val);
		const pathLabels = new Set();
		cityCascaderRef.value.getCheckedNodes().map((v: any) => {
			if (props.props.formatLabel) {
				pathLabels.add(props.props.formatLabel(v.pathLabels));
			} else {
				pathLabels.add(v.pathLabels);
			}
		});
		emit('update:label', props.props.multiple ? Array.from(pathLabels) : Array.from(pathLabels)[0]);
	},
});

onMounted(() => {
	getCityList().then((res) => {
		options.value = res.data;
	});
});
</script>
